<?php
/**
 * DEMO模板
 * power by huanran.zhao
 * QQ: 523994553
 * 2012-11-11
 */
class DemoApp extends CommonApp {
	/*
	I,$this->redirect('user/login');//跳转
	I,文章内容解码
		My::decodeHtml($result['content']);
	I,$a = DB('')->tables();// 获取当前数据库中的所有表。
	I,My::is_table('city');//判断表是否存在
	I,DB('dream_city')->getDbFields();//得到一个表的所有字段 (已有缓存机制)
	I,生成缓存文件,直接数组形式写入,不加密
		F('System', $data, DATA_DIR.'Config'.__DS__)
	I,得到缓存文件
		F('Config/System");//data目录下
	I,清除数据表缓存
		My::clear('city');
	I,在DB数据库操作函数函数中清缓存,删除当前数据表的数据(增/删/改)
		DB('datas')->where("id=1")->clear()->delete();
	I,数据库函数,如果存在删除相应记录再插入,没有就直接插入
		DB('table')->replace($data)
	I,是否存在表
		My::is_table('datas');
	I,import('Sdk.qq.app'); //导入文件: common/Sdk/qq/app.class.php   用来返回值的里面会return 而不是include
	I,common/tool下的类有两种调用方式: 
		静态调用My::aaa();和new aaa()
	I,判断是否存在模型:
		DB('datas')->isExists()
	I,输出执行时间:
		Log::output();//输出比较乱,最好用下面这个
	I,得到客户端ip函数: get_client_ip();
	I,加密html: htmlEscape()//在模板中的input中的value可以用这个以防""''报错
	I,保存params参数的白名单设置
		//params字段白名单(keepParams函数)
		$_POST['params'] = My::keepParams($_POST['params'],array('table'=>'datas','id'=>$id,'field'=>'id,title'));
		My::setParams('datas',$_POST['params'],$id,$item);//保存表单模型参数
		$ok = DB('datas')->save($_POST);
	I,判断编号是否重复
		$is_only = My::is_only('datas',array('id'=>$id,'field'=>'params.ID','value'=>$_POST['params']['ID'],'where'=>"A.`cat_id`={$_POST['cat_id']} AND A.`project`='{$parentShopId}'"));
		if($is_only)
			$this->ajaxReturn(300,'服务项目编号已经存在!');
	I,得到最后一条插入ID
		DB('')->insertID();
	I,删除数据前,将数据放入回收站: M('recycle')->set($table,$id);
	I,压缩html, Minify::compress($content);
	*/
	public function __construct(){
		$this->table = DB('datas');
	}

	//联立DEMO
	public function joinAct(){
		$item = 'worker';
		$cat_id = M('category')->item2id($item);
		if(!My::is_id($cat_id))
			$this->ajaxReturn(300,'分类错误!');
		//search
		$search = array();
		$search['where'] = "1 ";
		$search['where'] .= "AND A.`item`='{$item}' ";
		//publish
		if(My::arr2var($_REQUEST,'publish')=='0'){
			$search['where'] .= "AND A.publish=0 ";
		}else{
			$search['where'] .= "AND A.publish=1 ";
		}
		//time
		if(My::arr2var($_REQUEST,'s_time')!='' OR My::arr2var($_REQUEST,'e_time')!=''){
			$s_time = My::arr2var($_REQUEST,'s_time')?I('request.s_time'):date("Y-m").'-01';
			$e_time = My::arr2var($_REQUEST,'e_time')?I('request.e_time'):date("Y-m-d");
			$search['where'] .= "AND DATE_FORMAT(A.`adddate`,'%Y-%m-%d') between '{$s_time}' AND '{$e_time}' ";
		}
		$search['field'] = "A.*";
		$search['page'] = My::arr2var($_REQUEST,'page').(isset($_SESSION['pagesize'])?$_SESSION['pagesize']:'');//用于参与缓存标识
		$search['join'] = "#__bill as A ";
		$search['join'] .= "LEFT JOIN #__datas_params as B ON A.id=B.idid AND B.`type`='{$item}' ";
		$search['join'] .= "INNER JOIN #__datas_params as Q ON Q.`value`>0 AND Q.`key`='pay.qian' AND A.id=Q.idid ";
		$worker = I('request.worker');
		$search['join'] .= "INNER JOIN #__datas_params as E ON E.`value`='{$worker}' AND E.`key` LIKE 'tab1.worker%' AND A.id=E.idid ";//推荐这种可以走索引，下面的left/right函数走不了索引
		$search['join'] .= "INNER JOIN #__datas_params as F ON F.`value`='{$worker}' AND left(F.`key`,11)='tab1.worker' AND A.id=F.idid ";
		$result=My::getCache($search,array('pre'=>'bill'));
		if($result==''){
			//page
			$total_sql = DB('')->field('1')->join($search['join'])->where($search['where'])->group('A.id')->select(false);
			$result['page'] = My::page(My::sql2count($total_sql));
			//result
			$result['data'] = DB('')->field($search['field'])->join($search['join'])->where($search['where'])->group('A.id')->order('A.adddate DESC,A.id DESC')->limit($result['page']['limits'])->select();
			//echo DB('')->getLastSql();
			if(is_array($result['data']))
			foreach($result['data'] as &$value){
				$value['params'] = My::decodeJson($value['params']);
			}
			My::setCache($search,$result,array('pre'=>'bill'));
		}
		$this->assign('result',$result);
		if(My::arr2var($_GET,'tmpl')!='')
			$this->display('Datas/worker/'.My::arr2var($_GET,'tmpl'));
		else
			$this->display();
	}
	
	/**
	 * 首页
	 * @date 2012-11-24
	 * @author huanran.zhao
	 * @param array $title 标题		(整形int, 字符string, 数组array, 混合mixed, 序列化serialize)
	 * @return json		(json,html,xml,bool)
	*/
	public function indexAct(){
		//分页
		//$page = $this->page(23);
		//$result = $this->table->order("ordering ASC,id DESC")->limit($page['limits'])->select();
		//列表数据
		$result[]=array('id'=>'1','username'=>'赵先生','publish'=>1,'ordering'=>765);
		$result[]=array('id'=>'2','username'=>'黄先生','publish'=>0,'ordering'=>777);
		$this->assign("result",$result);
		//select
		$this->assign('select',array('1'=>'option1','2'=>'option2','3'=>'option3'));
		//radio
		$this->assign('radio',array('1'=>'是','0'=>'否'));
		//print_r($_GET);
		$this->display();
	}
		
	/**
	 * 编辑/添加 页面
	 * @params int $_GET['id']
	 */
	public function modifyAct(){
		$id = My::arr2var($_GET,'id');
		$result = array();
		if(My::is_id($id)){
			$result = DB('datas')->where("id={$id}")->find();
		}
		$this->assign('result',$result);
		$this->assign('publish',array(1=>'发布',0=>'不发布'));
		$this->display();
	}
	
	public function iframe_modifyAct(){
		$this->display();
	}
	
	/**
	 * 保存(编辑/添加)
	 * @params $_POST['url'] ->当前页面url
	 * @params $_POST['URL_'] -> 上一页面URL_
	 * @params $_POST['id'] -> 当前操作id(可选)
	 * @params $_POST -> post表单数据
	 */
	public function saveAct(){
		//echo "<pre>";print_r($_POST);exit;
		$id = My::arr2var($_POST,'id');
		if(My::is_id($id)){//编辑
			$ok = $this->table->save($_POST);
			if($ok)
				$this->ajaxReturn(200,"编辑成功");
			else
				$this->ajaxReturn(200,"编辑失败");
		}else{//添加
			$ok = $this->table->add($_POST);
			if($ok)
				$this->ajaxReturn(200,"添加成功");
			else
				$this->ajaxReturn(200,"添加失败");
		}
	}

	/**
	 * 留言板
	 */
	public function messageAct(){
		/*
		验证码生成函数:(放到functions.class.php类中)
			//获取验证码
			public function getVerifyCodeAct(){
				$config = array('imageW'=>100,'imageH'=>30,'fontSize'=>14,'useNoise'=>false,'fontttf'=>'5.ttf','length'=>4);
				$verify = new Verify($config);
				$verify->entry();
			}
		验证码图片:
			<img style="_width:60px;_height:25px;vertical-align:middle;margin-top:-3px;" src="{{$smarty.const.__PROJECT__}}index.php?app=functions&act=getVerifyCode" id="verifyCodeImg" onclick="this.src+='&' + Math.random();" align="top" class="verifycodeimg" title="点击刷新"/>
		日期选择date:
			{{include file="{{$smarty.const.PLUG}}date/date.html"}}
		JS:
			<script>
			//submit
			$('.submit').click(function(){
			    var params = $("form.form").serialize();
			    $.post('{{"index.php?app=about&act=message"|URL}}',params,function(result){
			        if(result.statusCode=='300'){
			            $('.verifycodeimg').click();
			            alert(result.message);
			        }
			        else if(result.statusCode=='200'){
			            alert(result.message);
			            document.location.reload();
						//document.location.href("{{'index.php?app=aaa&act=bbb'|URL}}");
			        }
			    },'json');
			});
			</script>
		*/
        if($_POST){
            $arr =  Array(
                'title' => '留言标题',
                'name' => '姓名',
                'tel' => '联系号码',
                'email' => '邮箱',
                'content' => '内容',
            );
            //foreach
            foreach($arr as $key=>$value){
                 //判断不能为空
                if(!in_array($key,array('tel')) AND trim(My::arr2var($_POST,$key))=='')//tel除外
                    $this->ajaxReturn(300,$value.'不能为空!');
                //判断是否为合格的字符串
                elseif(!in_array($key,array('tel')) AND !My::is_string(My::arr2var($_POST,$key),'c,e,n',"-,.@ 　\r\n\n\r"))//tel除外
                    $this->ajaxReturn(300,$value.'必须是(中文/英文/数字)!');
                //添加到data
                else
                    $data['params'][$key] = My::arr2var($_POST,$key);
            }
            //手机判断
            if(!Validator::isTelNumber($data['params']['tel']))
                $this->ajaxReturn(300,'手机号码格式有误!');
            //邮箱判断
            if(!Validator::isEmail($data['params']['email']))
                $this->ajaxReturn(300,'邮箱地址有误!');
            //验证码
			$verify = new Verify();
    		if(!$verify->check(My::arr2var($_POST,'verify')))
                $this->ajaxReturn(300,'验证码有误!');
        }
        //data
        $data['item'] = 'message';
        $data['title'] = $data['params']['title'];
        $data['adddate'] = date("Y-m-d H:i:s");
        $result = $data;
        $ok = DB('datas')->clear()->add($data);
        if($ok){
            $this->ajaxReturn(200,'提交成功!');
            /*
            ////发送邮件
            //邮箱标题
            $emailParam['title'] = '在线留言';
            //邮箱内容
            $this->assign('result',$result);
            $emailParam['content'] = $this->fetch('message/email');
            //收件人
            $emailParam['receiver'] = trim(C('email_receipt').','.My::arr2var($_POST,'sendmail'),',');
            $emailParam['receiver'] = My::explode(',',$emailParam['receiver']);
            $sendok = My::sendApiMail($emailParam);
            if($sendok==true)
                $this->ajaxReturn(200,'邮件发送成功!');
            else
                $this->ajaxReturn(200,'操作成功(邮件发送失败)!');
            */
        }
        else{
            $this->ajaxReturn(300,'提交失败!');
        }
    }

    /**
	 * 导出excel
	 */
	public function exportAct(){
		set_time_limit(0);
		$result = DB('')->cache()->query($sql);
		if(!$result OR !is_array($result))
			$this->ajaxReturn(300,'没有可导出的数据!');
		//print_r($result);die;
		$data[0] = array(
			'title' => '姓名', //
			'params.sex' => '性别', //
			'params.institutions' => '工作机构/就读学校', //
			'params.professional' => '专业', //
			'params.tel' => '手机号码', //
			'params.email' => '邮箱地址', //
			'params.identity' => '身份', //（在职/学生/社区）
			'params.isok_interview' => '面试是否通过', // 是/否
			'params.isok_resume' => '简历是否通过', // 是/否
			'params.isok_daolan' => '人工导览', // 是/否
			'params.isok_waiyu' => '外语能力', // 是/否
			'params.isok_photography' => '摄影录像', // 是/否
			'params.isok_design' => '平面设计', // 是/否
			'params.pingjia' => '面试评价', //
			'params.interviewer' => '面试官', //
			'params.interview_time' => '面试时间', //
			'params.beizhu' => '特别备注', //
			'params.server_time' => '累计服务时间', //
			'params.lose_time' => '流失时间', //
		);
		foreach($result as &$value){
			$value['params'] = My::decodeJson($value['params']);
			$value = My::customSort($value,array_flip($data[0]),true);
		}
		$data = array_merge($data, $result);
		//print_r($data);exit;
		$filename = 'VOLUNTEER';
		$filename = iconv('UTF-8','GBK',$filename);//转GBK，当$filename是中文的时候需要这行，不然会乱码
		$savepath = DATA_DIR.'/Cache/';
		$xls = new Excel('UTF-8', false, 'VOLUNTEER');
		$xls->addArray($data);
		$xls->saveXLS($filename, $savepath);
		$xls->downloadXLS($savepath.$filename, $filename);
		die;
		//$this->ajaxReturn(200,'导出成功!');
	}

    //日期转换(Excel的日期转成YYYY-MM-DD格式)
	private function  getDay($val){
	    $jd = GregorianToJD(1, 1, 1970);
	    $gregorian = JDToGregorian($jd+intval($val)-25569);
	    $gregorian = date('Y-m-d',strtotime($gregorian));
	    return $gregorian;/**显示格式为 “年-月-日” */
	}
	
	/**
	 * 读取Excel文档
	 * @param string $filePath excel文档路径
	 */
	private function readexcel( $filePath) {
	    require_once(COM_DIR."Excel/PHPExcel/IOFactory.php");
    	//默认用excel2007读取excel，若格式不对，则用之前的版本进行读取
    	$PHPReader = new PHPExcel_Reader_Excel2007();
    	if(!$PHPReader->canRead($filePath)){
    	    $PHPReader = new PHPExcel_Reader_Excel5();
    	    if(!$PHPReader->canRead($filePath)){
    	        self::showErr('无法读取Excel文档!');
    	    }
    	}
    	$PHPExcel = $PHPReader->load($filePath);
    	if(!$PHPExcel)
    	    self::showErr('无法读取Excel文档!');
    	//读取excel文件中的第一个工作表
    	$currentSheet = $PHPExcel->getSheet(0);
    	//取得最大的列号
    	$allColumn = $currentSheet->getHighestColumn();
    	//取得一共有多少行
    	$allRow = $currentSheet->getHighestRow();
    	//12个列标题
    	$title_arr = array(
    	    '日期',
    	    '渠道',
    	    '现公司',
    	    '姓名',
    	    '职位',
    	    '电话',
    	    '邮件',
    	    '地点',
    	    '毕业年限',
    	    '背景概要',
    	    '寻访记录',
    	    '状态',
    	);
    	//判断内容格式是否正确(12个标题是否完全匹配)
    	$error = array();
    	//注意，列数索引是从0开始
    	foreach($title_arr as $key=>$value){
    	    $title = $currentSheet->getCellByColumnAndRow($key,1)->getValue();
    	    if(trim($title)!=$value)
    	        $error[] = "Excel文档格式不符合要求，第".($key+1)."列正确的应该是“{$value}”";
    	}
    	if($error)
    	    self::showErr(My::implode('<br>',My::implode('<br>',$error)));
    	$result = array();
    	//从第二行开始输出，因为excel表中第一行为列名。
    	//注意，行数索引是从1开始
    	for($currentRow = 2;$currentRow <= $allRow;$currentRow++){
    	    $row = array();
    	    //从第0列开始输出
    	    foreach($title_arr as $kkk=>$vvv){
    	        $val = $currentSheet->getCellByColumnAndRow($kkk,$currentRow)->getValue();
    	        //空行判断(看必填列有没值，这里3是必填列，具体哪一列根据实际情况设置)
    	        if($kkk == 3 AND $val==''){
	                continue 2;
    	        }
    	        else if($kkk == 0)
    	        {
    	            if($val=='')
    	                $row[] = '';
    	            else
    	                $row[] = self::getDay($val);//日期格式转换
    	        }else{
    	            $row[] =  (string) $val;
    	        }
    	    }
    	    $result[] = $row;
    	}
    	//$result数组就是Excel的内容（不含列名）
    	return $result;
	}
	
	/**
	 * 导入excel
	 */
	public function importAct(){
	    if($_FILES){
	        if(isset($_FILES['xlsfile']['error']) AND $_FILES['xlsfile']['error']==4){
	            self::showErr('请选择Excle文件!');
	        }
	        set_time_limit(0);
	        include_once(PUB_DIR."share/plug/uploadfile/UploadFile.class.php");
	        $upload = new Upload();
	        //设置文件大小
	        $upload -> maxSize = 50*1024*1024;
	        //设置文件保存规则唯一
	        $upload->saveRule = 'uniqid';
	        //设置上传文件的格式
	        $upload -> allowExts = array('xls','xlsx');
	        //保存路径
	        $upload->savePath = ROOT_DIR.'/Data/MyCache/';
	        //设置需要生成缩略图，仅对图像文件有效
	        $upload->thumb = false;
	        //上传失败返回错误信息
	        if(!$upload->upload()){
	            self::showErr($upload->getErrorMsg());
	        }else{
	            $inf= $upload->getUploadFileInfo();
	            $xls_file = DATA_DIR.'MyCache/'.$inf[0]['savename'];
	        }
	        //读取excel内容
	        $xls = self::readexcel($xls_file);
	        if(!$xls)
	            self::showErr('读取不到有效的信息!');
	        $num = count($xls);
	        $result = array();
	        $error = array();
	        foreach($xls as $key=>&$value){
	            //渠道
	            $data['params']['channel'] = $value[1];
	            //姓名
	            $data['title'] = $value[3];
	            //公司
	            $data['params']['company'] = $value[2];
	            //职位
	            $data['params']['job'] = $value[4];
	            //手机
	            $data['tel'] = $value[5];
	            //email
	            $data['params']['email'] = $value[6];
	            //所在地
	            $data['params']['city'] = $value[7];
	            //毕业时间
	            $data['params']['employment_time'] = $value[8];
	            //背景概要
	            $data['params']['introduction'] = $value[9];
	            //寻访记录
	            $data['comment'] = array(
	                'content'=>$value[10],
	                'day'=>$value[0],
	            );
	            //原文
	            $title_arr = array(
	                '日期',
	                '渠道',
	                '现公司',
	                '姓名',
	                '职位',
	                '电话',
	                '邮件',
	                '地点',
	                '毕业年限',
	                '背景概要',
	                '寻访记录',
	                '状态',
	            );
	            $data['content'] = '';
	            foreach($title_arr as $kkk=>$vvv){
	                $data['content'].=$vvv.'：'.$value[$kkk].'<br>';
	            }
	            $data['adddate'] = date("Y-m-d H:i:s");
	            $data['author'] = My::user('username');
	            if($data['tel'] and DB('candidate')->where("tel='{$data['tel']}'")->cache()->count()>0)
	                $error[] = "（第".($key+2)."行）手机号：{$data['tel']} 已存在于数据库中!";
	            $result[] = $data;
	        }
	        if($error)
	            self::showErr(My::implode('<br>',$error));
	        if($result)
	            foreach($result as $key=>&$value){
	            $ok = DB('candidate')->clear()->add($value);
	            if($ok){
	                //保存表单模型参数
	                My::setParams('candidate',$value['params'],$ok,'candidate');
	                //添加寻访记录
	                if(My::arr2var($value,'comment.content')){
	                    $data['idid'] = $ok;
	                    $data['content'] = $value['comment']['content'];
	                    $data['user_id'] = My::user('userid');
	                    $data['author'] = My::user('username');
	                    $data['item'] = "comment";
	                    $data['table'] = "candidate";
	                    $data['title'] = $value['title'];
	                    $data['adddate'] = date("Y-m-d H:i:s");
                        $data['day'] = $value['comment']['day'];
                        $data['ip'] = get_client_ip();
                        $data['url'] = "http://".$_SERVER ['HTTP_HOST'].$_SERVER["REQUEST_URI"];
                        $ok = DB('comment')->clear()->add($data);
	                }
	            }else{
	                self::showErr('导入失败，db错误!');
	            }  
	        }
	        self::showSuc('导入成功!');
	    }
	    //display
	    $this->display();
	}
	
	private function showErr($str){
	    $str = str_replace("\n"," ",$str);
	    exit("<script>parent.err('{$str}')</script>");
	}
	
	private function showSuc($str){
	    exit("<script>parent.suc('{$str}')</script>");
	}

    /**
     * 头像上传(图片原生上传)
     */
    public function faceAct(){
        //判断是否已登录,如未登录则跳转到登录页面
        $this->checkLogin();
        $result = My::id2detail('member',My::arr2var($_SESSION,'member.id'));
        if($_FILES){
            if(isset($_FILES['headimage']['error']) AND $_FILES['headimage']['error']==4){
                $this->assign('error','请选择头像图片!');
                $this->display();
                exit();
                //上传头像为空
            }else{
                include_once(PUB_DIR."share/plug/uploadfile/UploadFile.class.php");
                $upload = new Upload();
                //设置文件大小
                $upload -> maxSize = 4096*1024;
                //设置文件保存规则唯一
                $upload->saveRule = 'uniqid';
                //设置上传文件的格式
                $upload -> allowExts = array('jpg','png','jpeg', 'gif', 'bmp');
                //保存路径
                $upload->savePath =PUB_DIR.'/share/images/uploads/';
                //设置需要生成缩略图，仅对图像文件有效
                $upload->thumb = false;
                //上传失败返回错误信息
                if(!$upload->upload()){
                    $this->assign('error',$upload->getErrorMsg());
                    $this->display();
                    exit();
                }else{
                    $inf= $upload->getUploadFileInfo();
                    $data['headimage'] = 'share/images/uploads/'.$inf[0]['savename'];
                }
            }
            $ok = DB('member')->where("id={$result['id']}")->clear()->save($data);
            if($ok>=0){
                M('admin.helper')->setLoginSession($result['id']);
                $this->assign('success','修改成功!');
            }else{
                $this->assign('error','修改失败!');
            }
        }
        //display
        $this->display();
    }
}